/**
  ******************************************************************************
  * @file    set_uart.c
  * @author  Hanif Rizal
  * @version V1.0.0
  * @date    03-Maret-2013
  * @brief   ATXmega UART access routine
  *              
  *  @verbatim
  *  
  *          ===================================================================
  *                                 How to use this driver
  *          ===================================================================              
  *   
  *  @endverbatim
  *    
  ******************************************************************************
  * @attention
  *
  * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
  * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
  * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
  * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
  * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
  * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
  *
  * <h2><center>&copy; COPYRIGHT 2013 Vibration Monitoring System TEAM</center></h2>
  ******************************************************************************
  */
#include "set_uart.h"

volatile char rx_buffer0[RX_BUFFER_SIZE0];
volatile unsigned char rx_wr_index0=0;
volatile unsigned char rx_rd_index0=0;
volatile unsigned char rx_counter0=0;
volatile char rx_buffer_overflow0=0;
char kal[50];

void myInit_UART(void)
{
	// Set the TxD pin high - set PORTC DIR register bit 3 to 1
	PORTC.OUTSET = PIN3_bm;
	// Set the TxD pin as an output - set PORTC OUT register bit 3 to 1
	PORTC.DIRSET = PIN3_bm;
	
	// Set the RxD pin as an input - set PORTC DIR register bit 2 to 0
	PORTC.DIRCLR = PIN2_bm;
	
	//Mode Asynchronous, disable parity, 1 stop bit, 8 bit char
	USARTC0.CTRLC= USART_CMODE_ASYNCHRONOUS_gc | USART_PMODE_DISABLED_gc | (0<<USART_SBMODE_bp) | USART_CHSIZE_8BIT_gc;
	
	//Set BaudRate 115200, BSCALE = -7 , BSEL=2094 (works @32MHz)
	USARTC0.BAUDCTRLA=0x2E;
	USARTC0.BAUDCTRLB=0x98;
	
	//Set BaudRate 9600, BSCALE = 0, BSEL=207 (works @32MHz)
	//USARTC0.BAUDCTRLA=0xCF;
	//USARTC0.BAUDCTRLB=0x00;
	
	//Enable RX dan TX
	USARTC0.CTRLB= USART_RXEN_bm | USART_TXEN_bm;
	
	//Enable RX Interrupt
	USARTC0.CTRLA = USART_RXCINTLVL_LO_gc;	
}

char myUART_Bufgetchar(void)
{
	static char data=0;
	
	//while (rx_counter0==0);
	data=rx_buffer0[rx_rd_index0++];
	
	if (rx_rd_index0 == RX_BUFFER_SIZE0) rx_rd_index0=0;
	cli();
	--rx_counter0;	//Atomic process
	sei();
	return data;
}

char usart_putchar(USART_t *usart, unsigned char c)
{
	while ( ((usart)->STATUS & USART_DREIF_bm) == 0) {
	}
	
	(usart)->DATA = c;
	return 1;
}

void myUART_Print(char *k)
{
	unsigned char i=0;
	
	while(k[i]!='\0')
	{
		usart_putchar(USART_C0,k[i]);
		i++;
	}
}